#!/bin/bash
set -e  # 遇到错误立即退出

# 定义 Redis 配置路径
REDIS_CONF_DIR="/home/codeme/redis/conf"
REDIS_CONF_FILE="$REDIS_CONF_DIR/redis.conf"
REDIS_ACL_FILE="$REDIS_CONF_DIR/users.acl"

# 创建目录
sudo mkdir -p "$REDIS_CONF_DIR"

# 生成 redis.conf 配置
cat > "$REDIS_CONF_FILE" <<EOF
# 允许本地和 Docker 访问
bind 0.0.0.0
port 6379
# ACL 配置
aclfile /usr/local/etc/redis/users.acl
EOF

# 生成 ACL 配置
PASS=$(cat /proc/sys/kernel/random/uuid)
echo "Generated Admin Password: $PASS"
echo "Generated Admin Password: $PASS" > password.txt

# ~* 允许所有频道 -CONFIG 防止修改 Redis 配置 
# allcommands 允许所有命令
# allkeys 允许所有键
# allchannels 允许所有频道
cat > "$REDIS_ACL_FILE" <<EOF
user default off nopass
user admin on >$PASS allcommands -CONFIG allkeys allchannels
EOF

# 确保 ACL 文件权限正确
sudo chmod 644 "$REDIS_ACL_FILE"

# 读取系统信息
if [ -f "/etc/os-release" ]; then
    . /etc/os-release
    case "$ID" in
        ubuntu|debian)
            echo "Detected Ubuntu/Debian, installing redis-cli..."
            sudo apt update && sudo apt install -y redis-tools
            ;;
        centos|rhel)
            echo "Detected CentOS/RHEL, installing redis..."
            sudo yum install -y redis
            ;;
        fedora)
            echo "Detected Fedora, installing redis..."
            sudo dnf install -y redis
            ;;
        alpine)
            echo "Detected Alpine Linux, installing redis..."
            sudo apk add redis
            ;;
        alinux)
            echo "Detected Alpine Linux, installing redis..."
            sudo apk add redis
            ;;
        *)
            echo "Unsupported Linux distribution: $ID"
            ;;
    esac
else
    echo "Unknown Linux distribution. Please install redis-cli manually."
fi

# 删除容器
docker rm -f redis 2>/dev/null

# 运行 Redis 容器
docker run --restart=always -d \
    -v "$REDIS_CONF_DIR:/usr/local/etc/redis" \
    -p 6380:6379 \
    --name redis \
    redis redis-server /usr/local/etc/redis/redis.conf
